package com.vstudy.zx.service.impl;

import com.vstudy.zx.dao.ArticleDao;
import com.vstudy.zx.entity.Article;
import com.vstudy.zx.service.MainService;
import com.vstudy.zx.utils.IOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class MainServiceImpl implements MainService {

    @Autowired
    private ArticleDao articleDao;

    @Override
    public List<Article> getRecentArticles(Integer pageIndex, Integer pageSize, HttpServletRequest request) {
        List<Article> articles = articleDao.selectPage((pageIndex - 1) * pageSize, pageSize);
        for (Article a :
                articles) {
            String path = a.getArticle_content();
//            path = request.getServletContext().getRealPath(path);
            try {
                String basePath = ResourceUtils.getURL("classpath:").getPath();
                path = basePath + "/static" + path;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }


            try {
                String content = IOUtil.readArticle(path, "utf-8");
                a.setArticle_content(content);
            } catch (IOException e) {
                e.printStackTrace();
            }

            a.releaseTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(a.getArticle_release_time());
        }
        return articles;
    }
}
